<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>个人信息</span>
      </div>
      <el-form ref="form" :model="userForm" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <div class="avatar-container">
              <div class="avatar-uploader">
                <img v-if="imageUrl" :src="getImageUrl(imageUrl)" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <input type="file" accept="image/*" class="avatar-input" @change="handleAvatarChange">
              </div>
              <el-button type="primary" size="small" @click="uploadAvatar" :loading="uploading">
                {{ uploading ? '上传中...' : '上传头像' }}
              </el-button>
            </div>
          </el-col>
          <el-col :span="16">
            <el-form-item label="用户ID" prop="id">
              <el-input v-model="userForm.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username"></el-input>
            </el-form-item>
            <el-form-item label="角色" prop="role">
              <el-input v-model="userForm.role" disabled></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateUserInfo" :loading="loading">保存修改</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getUserInfo, updateUserInfo, uploadAvatar } from '@/api/user'

export default {
  name: 'Profile',
  data() {
    const validatePhone = (rule, value, callback) => {
      const reg = /^1[3-9]\d{9}$/
      if (value && !reg.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (value && !reg.test(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    }
    const validateUsername = (rule, value, callback) => {
      if (!value || value.trim() === '') {
        callback(new Error('用户名不能为空'))
      } else if (value.length < 2 || value.length > 20) {
        callback(new Error('用户名长度应在2-20个字符之间'))
      } else {
        callback()
      }
    }
    return {
      userForm: {
        id: '',
        username: '',
        role: '',
        phone: '',
        email: '',
        avatar: ''
      },
      rules: {
        username: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        phone: [
          { required: false, trigger: 'blur', validator: validatePhone }
        ],
        email: [
          { required: false, trigger: 'blur', validator: validateEmail }
        ]
      },
      imageUrl: '',
      avatarFile: null,
      loading: false,
      uploading: false
    }
  },
  created() {
    this.fetchUserInfo()
  },
  methods: {
    fetchUserInfo() {
      // 从store中获取基本用户信息
      const userInfo = this.$store.getters.user
      const token = this.$store.getters.token

      console.log('Store中的用户信息:', userInfo)

      // 直接调用后端接口获取用户信息
      getUserInfo(token).then(response => {
        console.log('获取到的用户信息响应:', response)

        if (response.code === 200 && response.data) {
          const data = response.data
          console.log('用户数据:', data)

          // 设置用户信息
          if (data.user) {
            // 如果返回的是user对象
            const user = data.user
            this.userForm.id = user.id || ''
            this.userForm.username = user.username || ''
            this.userForm.role = user.role || ''
            this.userForm.phone = user.phone || ''
            this.userForm.email = user.email || ''
            this.userForm.avatar = user.avatar || ''
          } else {
            // 直接使用data
            this.userForm.id = data.id || ''
            this.userForm.username = data.username || data.name || ''
            this.userForm.role = data.roles || data.role || ''
            this.userForm.phone = data.phone || ''
            this.userForm.email = data.email || ''
            this.userForm.avatar = data.avatar || ''
          }

          // 如果角色是数组，转换为字符串显示
          if (Array.isArray(this.userForm.role)) {
            this.userForm.role = this.userForm.role.join(', ')
          }

          // 更新头像预览
          if (this.userForm.avatar) {
            this.imageUrl = this.userForm.avatar
          }

          console.log('设置后的用户表单:', this.userForm)
        }
      }).catch(error => {
        console.error('获取用户信息失败:', error)
        this.$message.error('获取用户信息失败')
      })
    },
    handleAvatarChange(e) {
      const file = e.target.files[0]
      if (!file) return

      // 验证文件类型
      const isImage = file.type.indexOf('image/') !== -1
      if (!isImage) {
        this.$message.error('请上传图片文件!')
        return
      }

      // 验证文件大小
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
        return
      }

      // 预览图片
      this.avatarFile = file
      const reader = new FileReader()
      reader.onload = (event) => {
        this.imageUrl = event.target.result
      }
      reader.readAsDataURL(file)
    },
    getImageUrl(url) {
      if (!url) return '';

      // 如果是相对路径，添加基础URL
      if (url.startsWith('/api/avatar/')) {
        // 将/api/avatar/替换为/avatar/
        const newUrl = url.replace('/api/avatar/', '/avatar/');
        console.log('转换旧URL:', process.env.VUE_APP_BASE_API + newUrl);
        return process.env.VUE_APP_BASE_API + newUrl;
      } else if (url.startsWith('/avatar/')) {
        // 直接添加基础API路径
        console.log('使用新URL:', process.env.VUE_APP_BASE_API + url);
        return process.env.VUE_APP_BASE_API + url;
      }

      // 如果已经是完整URL或者是数据URL，直接返回
      return url;
    },
    uploadAvatar() {
      if (!this.avatarFile) {
        this.$message.warning('请先选择头像图片')
        return
      }

      // 检查用户名是否存在
      if (!this.userForm.username) {
        this.$message.error('用户名不存在，无法上传头像')
        return
      }

      this.uploading = true

        const formData = new FormData()
  formData.append('file', this.avatarFile)
  // 移除username参数，由后端拦截器处理用户身份

      console.log('上传头像，用户名:', this.userForm.username)

      uploadAvatar(formData).then(response => {
        this.uploading = false
        if (response.code === 200) {
          this.$message.success('头像上传成功')
          this.userForm.avatar = response.data
          // 更新头像预览 - 使用getImageUrl方法
          this.imageUrl = this.getImageUrl(response.data)
          // 更新store中的头像
          this.$store.commit('user/SET_AVATAR', response.data)
        } else {
          this.$message.error(response.message || '头像上传失败')
        }
      }).catch(error => {
        this.uploading = false
        console.error('上传头像错误:', error)
        this.$message.error('头像上传失败: ' + (error.message || '未知错误'))
      })
    },
    updateUserInfo() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true

          // 创建一个新对象，只包含需要更新的字段
          const updateData = {
            id: this.userForm.id,
            username: this.userForm.username,
            phone: this.userForm.phone,
            email: this.userForm.email,
            avatar: this.userForm.avatar
          }

          updateUserInfo(updateData).then(response => {
            this.loading = false
            if (response.code === 200) {
              this.$message.success('个人信息更新成功')
              // 更新store中的用户信息
              this.$store.commit('user/SET_USER', {
                username: this.userForm.username,
                avatar: this.userForm.avatar,
                roles: this.userForm.role
              })
              // 更新头像
              if (response.data.avatar) {
                this.$store.commit('user/SET_AVATAR', response.data.avatar)
              }
              // 更新用户名
              this.$store.commit('user/SET_NAME', this.userForm.username)
            } else {
              this.$message.error(response.message || '个人信息更新失败')
            }
          }).catch(error => {
            this.loading = false
            console.error('更新个人信息错误:', error)
            this.$message.error('个人信息更新失败')
          })
        } else {
          return false
        }
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.fetchUserInfo()
    }
  }
}
</script>

<style scoped>
.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-uploader {
  position: relative;
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  margin-bottom: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}
</style>
